<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getUserProfile, updateUserProfile, uploadAvatar } from '@/api/index.js';
import useUserInfoStore from '@/store/user.js';

const store = useUserInfoStore();
const userInfo = ref({});
const loading = ref(true);
const editMode = ref(false);
const uploadLoading = ref(false);

// 用户类型映射表
const userTypeMap = {
  'ADMIN': '管理员',
  'TESTER': '测试员',
  'DEVELOPER': '开发人员',
  'MANAGER': '测试管理员',
  'VIEWER': '报告查看者'
};

// 表单数据
const form = reactive({
  username: '',
  first_name: '',
  last_name: '',
  email: '',
  phone_number: '',
  department: '',
  employee_id: '',
  avatar: ''
});

// 表单验证规则
const rules = reactive({
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone_number: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
});

// 获取用户信息
const fetchUserProfile = async () => {
  try {
    loading.value = true;
    const res = await getUserProfile();
    if (res.status === 200) {
      userInfo.value = res.data;
      // 填充表单数据
      Object.keys(form).forEach(key => {
        if (res.data[key]) {
          form[key] = res.data[key];
        }
      });
    } else {
      ElMessage.error('获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息出错:', error);
    ElMessage.error('网络错误，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 检查是否为管理员
const isAdmin = () => {
  return store.userInfo?.user_type === 'ADMIN' || userInfo.value?.user_type === 'ADMIN';
};

// 检查是否有管理权限
const hasManagePermission = () => {
  return store.userInfo?.user_type === 'ADMIN' || store.userInfo?.user_type === 'MANAGER';
};

// 头像上传处理
const handleAvatarUpload = async (file) => {
  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('只支持 JPEG、PNG、GIF、WebP 格式的图片');
    return false;
  }
  
  // 验证文件大小（2MB）
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过 2MB');
    return false;
  }
  
  try {
    uploadLoading.value = true;
    
    const formData = new FormData();
    formData.append('avatar', file);
    
    const res = await uploadAvatar(formData);
    if (res.status === 200) {
      ElMessage.success('头像上传成功');
      // 更新用户信息
      await fetchUserProfile();
      // 更新store中的头像（如果需要的话）
      if (res.data && res.data.avatar_url) {
        // 这里res.data.avatar_url是file_id，如果store需要完整URL，需要处理
        store.SetUserAvatar(res.data.avatar_url);
      }
    } else {
      ElMessage.error(res.msg || '头像上传失败');
    }
  } catch (error) {
    console.error('头像上传出错:', error);
    ElMessage.error('网络错误，请稍后再试');
  } finally {
    uploadLoading.value = false;
  }
  
  return false; // 阻止自动上传
};

// 获取默认头像
const getDefaultAvatar = () => {
  return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
};

// 获取头像URL
const getAvatarUrl = (avatar) => {
  if (!avatar) {
    return getDefaultAvatar();
  }
  
  // 如果已经是完整的URL，直接返回
  if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
    return avatar;
  }
  
  // 如果是file_id，通过/aps代理访问
  return `/aps/${avatar}`;
};

// 头像加载错误处理
const handleAvatarError = (event) => {
  console.warn('头像加载失败，使用默认头像');
  event.target.src = getDefaultAvatar();
};

// 切换编辑模式
const toggleEditMode = () => {
  editMode.value = !editMode.value;
  if (!editMode.value) {
    // 取消编辑，恢复原始数据
    Object.keys(form).forEach(key => {
      if (userInfo.value[key]) {
        form[key] = userInfo.value[key];
      } else {
        form[key] = '';
      }
    });
  }
};

// 提交表单
const formRef = ref(null);
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await updateUserProfile(form);
        if (res.status === 200) {
          ElMessage.success('个人信息更新成功');
          // 更新本地存储的用户信息
          if (res.data && store.userInfo) {
            // 更新用户头像
            if (form.avatar && form.avatar !== userInfo.value.avatar) {
              store.SetUserAvatar(form.avatar);
            }
          }
          // 刷新用户信息
          await fetchUserProfile();
          // 退出编辑模式
          editMode.value = false;
        } else {
          // 处理后端返回的错误信息
          if (typeof res.msg === 'object') {
            // 遍历错误对象，提取具体的错误信息
            let errorMessages = [];
            for (const [field, errors] of Object.entries(res.msg)) {
              if (Array.isArray(errors)) {
                errorMessages.push(...errors);
              } else {
                errorMessages.push(errors);
              }
            }
            ElMessage.error(errorMessages.join('; '));
          } else {
            ElMessage.error(res.msg || '更新失败，请稍后再试');
          }
        }
      } catch (error) {
        console.error('更新用户信息出错:', error);
        // 处理网络错误或其他异常
        if (error.response && error.response.data) {
          const errorData = error.response.data;
          if (typeof errorData.msg === 'object') {
            let errorMessages = [];
            for (const [field, errors] of Object.entries(errorData.msg)) {
              if (Array.isArray(errors)) {
                errorMessages.push(...errors);
              } else {
                errorMessages.push(errors);
              }
            }
            ElMessage.error(errorMessages.join('; '));
          } else {
            ElMessage.error(errorData.msg || '网络错误，请稍后再试');
          }
        } else {
          ElMessage.error('网络错误，请稍后再试');
        }
      }
    }
  });
};

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserProfile();
});
</script>

<template>
  <div class="user-profile-container">
    <el-card class="profile-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h2>个人中心</h2>
          <el-button 
            :type="editMode ? 'info' : 'primary'" 
            @click="toggleEditMode"
          >
            {{ editMode ? '取消编辑' : '编辑信息' }}
          </el-button>
        </div>
      </template>
      
      <div v-if="!editMode" class="info-display">
        <div class="avatar-section">
          <el-avatar 
            :size="100" 
            :src="getAvatarUrl(userInfo.avatar)" 
            @error="handleAvatarError"
          />
          <el-upload
            :before-upload="handleAvatarUpload"
            :show-file-list="false"
            accept="image/jpeg,image/png,image/gif,image/webp"
            style="margin-top: 10px"
          >
            <el-button 
              :loading="uploadLoading" 
              size="small" 
              type="primary"
            >
              {{ uploadLoading ? '上传中...' : '更换头像' }}
            </el-button>
          </el-upload>
        </div>
        
        <div class="info-section">
          <div class="info-item">
            <span class="label">用户名：</span>
            <span class="value">{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <span class="label">昵称：</span>
            <span class="value">{{ userInfo.nickname || '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户类型：</span>
            <span class="value">{{ userTypeMap[userInfo.user_type] || userInfo.user_type }}</span>
          </div>
          <div class="info-item">
            <span class="label">邮箱：</span>
            <span class="value">{{ userInfo.email }}</span>
          </div>
          <div class="info-item">
            <span class="label">手机号：</span>
            <span class="value">{{ userInfo.phone_number }}</span>
          </div>
          <div class="info-item">
            <span class="label">部门：</span>
            <span class="value">{{ userInfo.department_name || '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">员工编号：</span>
            <span class="value">{{ userInfo.employee_id || '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">注册时间：</span>
            <span class="value">{{ new Date(userInfo.date_joined).toLocaleString() }}</span>
          </div>
          <div class="info-item">
            <span class="label">最后登录：</span>
            <span class="value">{{ userInfo.last_login ? new Date(userInfo.last_login).toLocaleString() : '从未登录' }}</span>
          </div>
          <div class="info-item">
            <span class="label">测试创建数：</span>
            <span class="value">{{ userInfo.tests_created || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="label">测试执行数：</span>
            <span class="value">{{ userInfo.tests_executed || 0 }}</span>
          </div>
        </div>
      </div>
      
      <el-form 
        v-else 
        ref="formRef"
        :model="form" 
        :rules="rules"
        label-position="top"
        class="edit-form"
      >
        <div class="avatar-section">
          <el-avatar 
            :size="100" 
            :src="getAvatarUrl(form.avatar)" 
            @error="handleAvatarError"
          />
          <el-upload
            :before-upload="handleAvatarUpload"
            :show-file-list="false"
            accept="image/jpeg,image/png,image/gif,image/webp"
            style="margin-top: 10px"
          >
            <el-button 
              :loading="uploadLoading" 
              size="small" 
              type="primary"
            >
              {{ uploadLoading ? '上传中...' : '更换头像' }}
            </el-button>
          </el-upload>
        </div>
        
        <div class="form-section">
          <el-form-item label="用户名">
            <el-input v-model="form.username" disabled />
            <small class="form-tip">用户名不可修改</small>
          </el-form-item>
          
          <el-form-item label="姓名">
            <el-input v-model="form.first_name" placeholder="请输入姓" />
          </el-form-item>
          
          <el-form-item label="名字">
            <el-input v-model="form.last_name" placeholder="请输入名" />
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          
          <el-form-item label="手机号" prop="phone_number">
            <el-input v-model="form.phone_number" />
          </el-form-item>
          
          <el-form-item label="部门">
            <el-input v-model="form.department_name" :disabled="!hasManagePermission()" readonly />
            <small v-if="!hasManagePermission()" class="form-tip">部门由管理员分配</small>
          </el-form-item>
          
          <el-form-item label="员工编号">
            <el-input v-model="form.employee_id" :disabled="!hasManagePermission()" readonly />
            <small v-if="!hasManagePermission()" class="form-tip">员工编号由管理员分配</small>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="toggleEditMode">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<style lang="less" scoped>
.user-profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h2 {
      margin: 0;
      font-size: 20px;
      color: #333;
    }
  }
}

.info-display {
  display: flex;
  flex-wrap: wrap;
  
  .avatar-section {
    display: flex;
    justify-content: center;
    width: 100%;
    margin-bottom: 20px;
  }
  
  .info-section {
    width: 100%;
    
    .info-item {
      margin-bottom: 12px;
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      
      .label {
        font-weight: bold;
        width: 100px;
        color: #606266;
      }
      
      .value {
        flex: 1;
        color: #303133;
      }
    }
  }
}

.edit-form {
  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
    
    .el-form-item {
      width: 100%;
      max-width: 400px;
      margin-top: 10px;
    }
  }
  
  .form-section {
    max-width: 500px;
    margin: 0 auto;
  }
  
  .form-tip {
    color: #909399;
    font-size: 12px;
  }
}

@media (min-width: 768px) {
  .info-display {
    .avatar-section {
      width: 30%;
      align-items: flex-start;
      margin-bottom: 0;
    }
    
    .info-section {
      width: 70%;
    }
  }
}
</style> 